package com.hui.modules.comm.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import com.hui.modules.sys.model.User;
import com.hui.utils.Convert;
import com.hui.utils.jedis.MyJedis;


/**
 * @ClassName: 基本控制类 (BaseController.java)
 * 
 * @Description: 提供一些在控制层中常用的方法
 * 
 * @Date: 2014年8月6日 10:29:59
 * @Author liuwei
 */
@Controller
public class BaseController {
	public static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	public MyJedis myJedis = MyJedis.getInstance();
	
	public BaseController() {
	}
	
	public static User getUser(){
		User user = (User) SecurityUtils.getSubject().getPrincipal();;
		return user;
	}
	public static Long getUserId(){
		return getUser().getUserId();
	}
	
	public static Long getUserDeptId(){
		return getUser().getDeptId();
	}
	

	protected static void flushResponse(HttpServletResponse response,
			String responseContent) {

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.write(responseContent);
		} catch (IOException e) {
			logger.error("error:{}",e);
		} finally {
			writer.flush();
			writer.close();
		}

	}

	

	/**
	 * <p>
	 * 从request中获取参数根据键值对形成Map. <br>
	 * 注意:对于数组参数，只拷贝了第1个元素.<br>
	 * 对于全空格的数据，仍然保留，在保存修改时可能需要.
	 * </p>
	 * 
	 * @param request
	 * @return map
	 */
	protected static Map<String, Object> getParamValues(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		@SuppressWarnings("rawtypes")
		Enumeration names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String key = (String) names.nextElement();
			String value = request.getParameter(key);
			if (value != null && value != "") {
				map.put(key, value);
			}
		}
		return map;
	}
	/**
	 * 页面刷新处理
	 * @param msg 操作成功提示
	 * @param submitFunName 查询列表中的查询表单提交方法
	 * @param ifCloseWindow 是否需要关闭当前窗口
	 * @return
	 */
	protected ModelAndView refurbish(String msg,String submitFunName,boolean ifCloseWindow){
		ModelAndView mav = new ModelAndView("/common/failure");
		mav.addObject("msg",msg);
		mav.addObject("submitFunName",submitFunName);
		mav.addObject("ifCloseWindow",ifCloseWindow);
		return mav;	
	}

	/**
	 * 获得当前页码
	 * @Time 2014年8月6日 10:31:18
	 * @param request
	 * @return int
	 */
	protected static int getCurrentPageNum(HttpServletRequest request) {
		String pageNum = request.getParameter("pageNum");
		return Integer.parseInt(pageNum);
	}
	
	/**
	 * 获得每页大小
	 * @Time 2014年8月6日 10:31:18
	 * @param request
	 * @return int
	 */
	protected static int getNumPerPage(HttpServletRequest request) {
		String numPerPage = request.getParameter("numPerPage");
		return Integer.parseInt(numPerPage);
	}

	/**
	 * 
	 * @return
	 */
	public void FlushBytes(byte[] date,HttpServletResponse response){
		InputStream in = null;
		OutputStream outStream = null;
		try {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			in = new ByteArrayInputStream(date);
			outStream = response.getOutputStream();
			byte[] buf = new byte[1024];
			int bytes = 0;
			while ((bytes = in.read(buf)) != -1) {
			    outStream.write(buf, 0, bytes);
			}
			in.close();
            outStream.flush();
            outStream.close();
            outStream = null;
            response.flushBuffer();
		} catch (IOException e) {
			//e.printStackTrace();
		}finally{
			try {
				if(in!=null){
					in.close();
				}
				if(outStream!=null){
					outStream.close();
				}
			} catch (IOException e) {
				//e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获得当前的页数
	 * @Time 2014年8月6日 10:31:18
	 * @param request
	 * @return int 
	 */
	protected static int getCurrentpageNumber(HttpServletRequest request) {		
		return getCurrentpageNumber(request,1);
	}
	
	/**
	 * 获得当前的页数
	 * @Time 2014年8月6日 10:31:18
	 * @param request
	 * @param defaultpageNumber 默认页数
	 * @return int 
	 */
	protected static int getCurrentpageNumber(HttpServletRequest request,int defaultpageNumber) {
		String pageNumber = request.getParameter("pageNumber");
		try {
			if(null!=pageNumber && !"".equals(pageNumber)){
				return Integer.parseInt(pageNumber);
			}
		} catch (Exception e) {			
			//e.printStackTrace();
		}
		return defaultpageNumber;
	}
	
	/**
	 * 获得每页的行数
	 * @Time 2014年8月6日 10:31:18
	 * @param request
	 * @param defaultPageSize 默认的每页行数
	 * @return int 
	 */
	protected static int getCurrentpageSize(HttpServletRequest request,int defaultPageSize) {
		String pageSize = request.getParameter("pageSize");
		try {
			if(null!=pageSize && !"".equals(pageSize)){
				return Integer.parseInt(pageSize);
			}
		} catch (Exception e) {			
			//e.printStackTrace();
		}
		return defaultPageSize;
	}	
	
	
	/**
	 * 相关分页信息
	 * @Time 2014年8月6日 10:31:18
	 * @param map
	 * @param request
	 * @return
	 */
	public Map<String, Object> pageXX(Map<String, Object> map,
			HttpServletRequest request) {
		int pageSize = 10;
		int pageNumber = 1;
		String pageSizes = request.getParameter("pageSize");
		String pageNumbers = request.getParameter("pageNumber");
		if (null != pageSizes && !"".equals(pageSize)) {
			pageSize = Convert.getInteger(pageSizes);
		}
		if (null != pageNumbers && !"".equals(pageNumbers)) {
			pageNumber = Convert.getInteger(pageNumbers);
		}
		map.put("rows", pageSize);
		map.put("page", (pageNumber-1)*pageSize);
		return map;
	}
	

	
	
	/**
	 * 从request中获取参数根据键值对形成 Map<String,String[]>. 
	 * 对于全空格的数据，仍然保留，在保存修改时可能需要.
	 * @param request
	 * @return map
	 */
	protected static Map<String, String[]> getParameterValues(
			HttpServletRequest request) {
		Map<String, String[]> paramValues = new HashMap<String, String[]>();
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String key =names.nextElement();
			String value[] = request.getParameterValues(key);
			paramValues.put(key, value);
		}
		return paramValues;
	}

}
